<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--空间位置数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            maxlength="0"
            v-model="filterText"
            placeholder="请输入位置信息"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="locationOptions"
            :props="defaultLocation"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--水电设备数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item label="设备编号" prop="deviceCode">
            <el-input
              v-model="queryParams.deviceCode"
              placeholder="请输入设备编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="设备名称" prop="deviceName">
            <el-input
              v-model="queryParams.deviceName"
              placeholder="请输入设备名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['example:device:add']"
            >新增设备
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
          <!--        <el-table-column type="selection" width="55" align="center"/>-->
          <el-table-column label="序号" align="center" prop="id" fixed/>
          <el-table-column label="设备名称" align="center" prop="deviceName" width="100"/>
          <el-table-column label="设备状态" align="center" prop="deviceStatus" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.deviceStatus == 0 ? 'success':'danger'">
                {{selectDictLabel(dict.type.device_status,scope.row.deviceStatus)}}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="设备位置" align="center" prop="nameDEVICE" width="160"/>
          <el-table-column label="设备编号" align="center" prop="deviceCode" width="160"/>
          <el-table-column label="设备类型" align="center" prop="deviceType" width="120" :formatter="deviceTypeFormatter"/>
          <el-table-column label="设备剩余金额" align="center" prop="deviceBalance" width="100"
                           :formatter="deviceBalanceFormatter"/>
          <el-table-column label="设备剩余量" align="center" prop="deviceSurplus" width="100"
                           :formatter="deviceSurplusFormatter"/>
          <el-table-column label="水表阀门状态" align="center" prop="sluiceStatus" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.sluiceStatus == 0 ? 'success':'danger'"
                      v-if="scope.row.deviceType == 2 && scope.row.sluiceStatus != '' && scope.row.sluiceStatus != null">
                {{selectDictLabel(dict.type.sluice_stauts,scope.row.sluiceStatus)}}
              </el-tag>
              <el-link
                v-if="scope.row.deviceType != 2 || scope.row.sluiceStatus == '' || scope.row.sluiceStatus == null">-
              </el-link>
            </template>
          </el-table-column>
          <el-table-column label="电表总状态" align="center" prop="electricityStatus" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.electricityStatus == 0 ? 'success':'danger'"
                      v-if="scope.row.deviceType != 2 && scope.row.electricityStatus != '' && scope.row.electricityStatus != null">
                {{selectDictLabel(dict.type.gate_on_off,scope.row.electricityStatus)}}
              </el-tag>
              <el-link
                v-if="scope.row.deviceType == 2 || scope.row.electricityStatus == '' || scope.row.electricityStatus == null">
                -
              </el-link>
            </template>
          </el-table-column>
          <el-table-column label="电表A路状态" align="center" prop="electricityAStatus" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.electricityAStatus == 0 ? 'success':'danger'"
                      v-if="scope.row.deviceType != 2 && scope.row.electricityAStatus != '' && scope.row.electricityAStatus != null">
                {{selectDictLabel(dict.type.gate_on_off,scope.row.electricityAStatus)}}
              </el-tag>
              <el-link
                v-if="scope.row.deviceType == 2 || scope.row.electricityAStatus == '' || scope.row.electricityAStatus == null">
                -
              </el-link>
            </template>
          </el-table-column>
          <el-table-column label="电表B路状态" align="center" prop="electricityBStatus" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.electricityBStatus == 0 ? 'success':'danger'"
                      v-if="scope.row.deviceType != 2 && scope.row.electricityBStatus != '' && scope.row.electricityBStatus != null">
                {{selectDictLabel(dict.type.gate_on_off,scope.row.electricityBStatus)}}
              </el-tag>
              <el-link
                v-if="scope.row.deviceType == 2 || scope.row.electricityBStatus == '' || scope.row.electricityBStatus == null">
                -
              </el-link>
            </template>
          </el-table-column>
          <el-table-column label="入网时间" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" align="center" width="180" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-tooltip content="编辑" placement="top">
                <el-button
                  circle
                  size="small"
                  type="primary"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['example:device:edit']"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  circle
                  size="small"
                  type="danger"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['example:device:remove']"
                >
                </el-button>
              </el-tooltip>
              <el-tooltip content="重新开户" placement="top" v-if="scope.row.deviceType == 1">
                <el-button
                  circle
                  size="small"
                  type="warning"
                  icon="el-icon-refresh"
                >
                </el-button>
              </el-tooltip>
              <el-dropdown trigger="click" size="mini" @command="(command) => handleCommand(command, scope.row)"
                           v-hasPermi="['example:device:edit', 'example:device:edit']">
                <el-tooltip content="操作" placement="top">
                  <el-button
                    circle
                    size="small"
                    type="info"
                    icon="el-icon-setting"
                  >
                  </el-button>
                </el-tooltip>
                <el-dropdown-menu slot="dropdown" v-if="scope.row.deviceType != 2">
                  <el-dropdown-item command="handleElectricityStatus" icon="el-icon-top"
                                    v-hasPermi="['example:device:edit']">拉总电闸
                  </el-dropdown-item>
                  <el-dropdown-item command="handleElectricityStatusG" icon="el-icon-bottom"
                                    v-hasPermi="['example:device:edit']">合总电闸
                  </el-dropdown-item>

                  <el-dropdown-item command="handleElectricityAStatus" icon="el-icon-sort-up"
                                    v-hasPermi="['example:device:edit']">拉A路电闸
                  </el-dropdown-item>
                  <el-dropdown-item command="handleElectricityAStatusG" icon="el-icon-sort-down"
                                    v-hasPermi="['example:device:edit']">合A路电闸
                  </el-dropdown-item>
                  <el-dropdown-item command="handleElectricityBStatus" icon="el-icon-sort-up"
                                    v-hasPermi="['example:device:edit']">拉B路电闸
                  </el-dropdown-item>
                  <el-dropdown-item command="handleElectricityBStatusG" icon="el-icon-sort-down"
                                    v-hasPermi="['example:device:edit']">合B路电闸
                  </el-dropdown-item>
                </el-dropdown-menu>

                <el-dropdown-menu slot="dropdown" v-if="scope.row.deviceType == 2">
                  <el-dropdown-item command="handleSluiceStatus" icon="el-icon-top"
                                    v-hasPermi="['example:device:edit']">开阀门
                  </el-dropdown-item>
                  <el-dropdown-item command="handleSluiceStatusG" icon="el-icon-bottom"
                                    v-hasPermi="['example:device:edit']">关阀门
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物联设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="设备编号" prop="deviceCode">
              <el-input v-model="form.deviceCode" placeholder="请输入设备编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="form.deviceType" placeholder="请输入设备类型">
                <el-option v-for="item in dict.type.device_type" :label="item.label" :key="item.value"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName" placeholder="请输入设备名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="空间位置" prop="bsloId">
              <treeselect v-model="form.bsloId" :options="locationOptions" :show-count="true" placeholder="请输入空间位置"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" v-if="form.id != null">
          <el-col :span="24">
            <el-form-item label="所属网关" prop="gatewayId">
              <el-select v-model="form.gatewayId" placeholder="请输入所属网关">
                <el-option v-for="item in gatewayOptions"
                           :label="item.gatewayName"
                           :key="item.id + ''"
                           :value="item.id + ''"
                           :disabled="item.status == 1"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {handlerGateSwitch} from "../../../api/wlw/Iotdevice";
  import {listGateway} from "../../../api/example/gateway";
  import {listDevice, getDevice, delDevice, addDevice, updateDevice} from "@/api/example/device";
  import {listLocation, getLocation, delLocation, addLocation, updateLocation} from "@/api/chart/location";
  import {getToken} from "@/utils/auth";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    name: "Device",
    dicts: ['device_status', 'device_type', 'gate_on_off', 'sluice_stauts'],
    components: {Treeselect},
    data() {
      return {
        // 位置信息
        filterText: undefined,
        // 空间位置树选项
        locationOptions: undefined,
        // 空间位置数据
        defaultLocation: {
          children: 'children',
          label: 'locationName',
        },
        // 所属网关
        gatewayOptions: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 物联设备表格数据
        deviceList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          gatewayId: null,
          deviceCode: null,
          deviceType: null,
          deviceName: null,
          deviceStatus: null,
          deviceLocation: null,
          rechargeCount: null,
          deviceBalance: null,
          deviceSurplus: null,
          totle: null,
          deviIp: null,
          deviUsername: null,
          deviPassword: null,
          deviSdkPort: null,
          deviAccessType: null,
          deviOpenAlwaysTimeIndex: null,
          deviCloseAlwaysTimeIndex: null,
          bsloId: null,
          deviOtherInfo: null,
          surplusUnit: null,
          sluiceStatus: null,
          electricityStatus: null,
          electricityAStatus: null,
          electricityBStatus: null,
          modifyTime: null,
          modifyBy: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          deviceCode: [{required: true, message: '设备编号不能为空', trigger: 'blur'}],
          deviceType: [{required: true, message: '设备类型不能为空', trigger: 'blur'}],
          deviceName: [{required: true, message: '设备名称不能为空', trigger: 'blur'}],
          bsloId: [{required: true, message: '空间位置不能为空', trigger: 'blur'}],
        }
      };
    },
    watch: {
      // 根据位置名称筛选部门树
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
    created() {
      this.getList();
      this.getDeptTree();
    },
    methods: {
      /** 查询物联设备列表 */
      getList() {
        this.loading = true;
        listDevice(this.queryParams).then(response => {
          this.deviceList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          gatewayId: null,
          deviceCode: null,
          deviceType: null,
          deviceName: null,
          deviceStatus: null,
          deviceLocation: null,
          rechargeCount: null,
          deviceBalance: null,
          deviceSurplus: null,
          totle: null,
          deviIp: null,
          deviUsername: null,
          deviPassword: null,
          deviSdkPort: null,
          deviAccessType: null,
          deviOpenAlwaysTimeIndex: null,
          deviCloseAlwaysTimeIndex: null,
          bsloId: null,
          deviOtherInfo: null,
          surplusUnit: null,
          sluiceStatus: null,
          electricityStatus: null,
          electricityAStatus: null,
          electricityBStatus: null,
          createTime: null,
          createBy: null,
          modifyTime: null,
          modifyBy: null
        };
        this.resetForm("form");
        this.getDeptTree();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加设备信息";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getDevice(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改设备信息";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateDevice(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addDevice(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除物联设备编号为"' + ids + '"的数据项？').then(function () {
          return delDevice(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('example/device/export', {
          ...this.queryParams
        }, `device_${new Date().getTime()}.xlsx`)
      },
      // 空间位置数据
      /** 空间位置下拉树结构 */
      getDeptTree() {
        listGateway().then(resp => {
          this.gatewayOptions = [];
          this.gatewayOptions = resp.rows;
        })
        listLocation().then(response => {
          this.locationOptions = [];
          // this.locationList = response.data;
          const data = {id: 0, locationName: '目录', children: []};
          data.children = this.handleTree(response.data, "id", "locationPid");
          this.locationOptions.push(data);
          // this.locationOptions = this.handleTree(response.data, "id", "locationPid");
          console.log(this.locationOptions);
        });
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.deviceLocation = data.id;
        this.queryParams.deviceLocation == 0 ? this.queryParams.deviceLocation = undefined : this.queryParams.deviceLocation = data.id;
        this.handleQuery();
      },
      /** 转换基础信息空间位置数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.locationName,
          children: node.children,
        };
      },

      // 设备类型
      deviceTypeFormatter(row) {
        return this.selectDictLabel(this.dict.type.device_type, row.deviceType);
      },
      // 设备剩余金额
      deviceBalanceFormatter(row) {
        if (row.deviceBalance == null || row.deviceBalance == undefined) {
          return "-";
        } else if (row.deviceBalance == '') {
          return "0.0元"
        }
        return row.deviceBalance + "元";
      },
      // 设备剩余量
      deviceSurplusFormatter(row) {
        if (row.deviceSurplus == null || row.deviceSurplus == undefined) {
          return "-";
        } else if (row.deviceSurplus == '' && row.deviceType == 2) {
          return "0.0吨";
        }
        if (row.deviceType != 2 && row.deviceSurplus != '') {
          return parseFloat(row.deviceSurplus).toFixed(2) + "度";
        } else if (row.deviceSurplus == '') {
          return "0.0度";
        }
        return row.deviceSurplus + "吨";
      },

      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "handleSluiceStatus":
            this.handleSluiceStatus(row);
            break;
          case "handleSluiceStatusG":
            this.handleSluiceStatusG(row);
            break;

          case "handleElectricityStatus":
            this.handleElectricityStatus(row);
            break;
          case "handleElectricityStatusG":
            this.handleElectricityStatusG(row);
            break;

          case "handleElectricityAStatus":
            this.handleElectricityAStatus(row);
            break;
          case "handleElectricityAStatusG":
            this.handleElectricityAStatusG(row);
            break;

          case "handleElectricityBStatus":
            this.handleElectricityBStatus(row);
            break;
          case "handleElectricityBStatusG":
            this.handleElectricityBStatusG(row);
            break;

          default:
            break;
        }
      },
      // 水表
      handleSluiceStatus(row) {
        handlerGateSwitch({deviceCode: (row.deviceCode), gatewayId: (row.gatewayId), waterStatus: 1}).then()
      },
      handleSluiceStatusG(row) {
        handlerGateSwitch({deviceCode: (row.deviceCode), gatewayId: (row.gatewayId), waterStatus: 0}).then()
      },
      // 总电表
      handleElectricityStatus(row) {
        handlerGateSwitch({deviceCode: (row.deviceCode), gatewayId: (row.gatewayId), electricityStatus: 0}).then()
      },
      handleElectricityStatusG(row) {
        handlerGateSwitch({deviceCode: (row.deviceCode), gatewayId: (row.gatewayId), electricityStatus: 1}).then()
      },
      // A路电表
      handleElectricityAStatus(row) {
        handlerGateSwitch({deviceCode: (row.deviceCode), gatewayId: (row.gatewayId), electricityAStatus: 0}).then()
      },
      handleElectricityAStatusG(row) {
        handlerGateSwitch({deviceCode: (row.deviceCode), gatewayId: (row.gatewayId), electricityAStatus: 1}).then()
      },
      // B路电表
      handleElectricityBStatus(row) {
        handlerGateSwitch({deviceCode: (row.deviceCode), gatewayId: (row.gatewayId), electricityBStatus: 0}).then()
      },
      handleElectricityBStatusG(row) {
        handlerGateSwitch({deviceCode: (row.deviceCode), gatewayId: (row.gatewayId), electricityBStatus: 1}).then()
      },
    }
  };
</script>
